#include "Plane.h"

Plane::Plane(vec4 _pos, vec3 _rot, vec4 _upVec):Shape(_pos, _rot){
	upVec = normalize(_upVec);
}


Plane::~Plane(){
}

bool Plane::intersect(Intersection &_int){
	Stats::instance()->primTest();	//increment the intersection test count
	//ray-plane intersection test
	//  http://www.scratchapixel.com/lessons/3d-basic-lessons/lesson-7-intersecting-simple-shapes/ray-plane-and-ray-disk-intersection/

	Ray _theRay = *(_int.ray());
	vec3 norm = upVec.xyz();
	vec3 planePos = pos.xyz();
	vec3 rayOrigin = _theRay.origin();
	vec3 rayDirection = _theRay.direction();
	
	float denominator = dot(norm, rayDirection);

	if (denominator >= 0.0f){
		return false;
	}
	float _dist = (dot(planePos, norm) - dot(rayOrigin, norm)) / dot(rayDirection, norm);
	
	//if the intersection is too close or too far
	if (_dist < _theRay.minDist() || _dist > _theRay.maxDist()){
		return false;
	}
	//if the intersection is the closest
	if (_dist < _int.dist()){
		//set the new closest distance
		_int.dist(_dist);
		//set the new closest shape
		_int.shape(this);
		//set the surface normal at the intersection point
		_int.surfNorm(upVec.xyz());
	}
	//notify the Intersection that it has intersected
	_int.intersected(true);
	Stats::instance()->primInt();	//increment the intersection count
	return true;
}

vec4 Plane::getColor(Intersection &_int){
	//calculate the surface color based on the Plane's ShaderCollection
	if (shade == NULL){
		return vec4(0, 0.2, 0, 0);
	}
	return shade->getColor(_int);
}

vec3 Plane::getCenter(){
	return pos.xyz;
}